Java时间日期和时间戳相互转换

您所在的位置:网站首页 java 时间戳转日期 Java时间日期和时间戳相互转换

Java时间日期和时间戳相互转换

#Java时间日期和时间戳相互转换| 来源: 网络整理| 查看: 265

public static void main(String[] args) throws Exception{ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); System.out.println(sdf.format(new Date())); //获取当前时间戳,也可以是你自已给的一个随机的或是别人给你的时间戳(一定是long型的数据) long timeStamp = System.currentTimeMillis(); logger.info("timeStamp:"+timeStamp); //这个是你要转成后的时间的格式 SimpleDateFormat sdff=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 时间戳转换成时间 String sd = sdff.format(new Date()); System.out.println("sd:"+sd);//打印出你要的时间 dateToStamp(sd); System.out.println("dateToStamp(sd):"+dateToStamp(sd));

long time = 30*60*1000;//30分钟 Date beforeDate = new Date((new Date()).getTime() - time);//30分钟前的时间 System.out.println("beforeDate:"+beforeDate);  //时间格式转换 SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM d HH:mm:ss 'CST' yyyy", Locale.ENGLISH); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format1 = sdf2.format(sdf1.parse(beforeDate.toString())); System.out.println("format1:"+format1); System.out.println("beforeDate:"+dateToStamp(format1));

}

//将时间转换为时间戳public static String dateToStamp(String s) throws ParseException { String res; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = simpleDateFormat.parse(s); long ts = date.getTime(); res = String.valueOf(ts); return res;}

//将时间戳转换为时间public static String stampToDate(String s){ String res; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); long lt = new Long(s); Date date = new Date(lt); res = simpleDateFormat.format(date); logger.info("res:"+res); return res;}



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3